package com.wangzeqi.changliaoba.login;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.parse.ParseObject;
import com.wangzeqi.changliaba.dao.User;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.base.LogBase;
import com.wangzeqi.changliaoba.login.enter.EaseCommonUtils;
import com.wangzeqi.changliaoba.singleton.AllSingleTon;


public class EnterActivity extends BaseActivity implements View.OnClickListener {

    private EditText editPerson, editCode;
    private TextView textViewF, textViewR, textViewQ, textView_phone_login;
    private ImageView imageView, imageViewClose;
    private Button btn;
    private LogBase log;
    String name = null;
    String num = null;
    private boolean autoLogin = false;
    public static String currentUsername;
    private String currentPassword;
    private boolean progressShow;
    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 如果登录成功过，直接进入主页面 自动登陆
        if (EMChat.getInstance().isLoggedIn()) {
            autoLogin = true;
            startActivity(new Intent(this, MainActivity.class));
            return;
        }
        setContentView(R.layout.activity_enter);
        btn = (Button) findViewById(R.id.enter_btn);
        btn.setOnClickListener(this);
        editCode = (EditText) findViewById(R.id.enter_code);
        editPerson = (EditText) findViewById(R.id.enter_name);
        textViewF = (TextView) findViewById(R.id.forget_code);
        textViewR = (TextView) findViewById(R.id.register_tv);
        textViewQ = (TextView) findViewById(R.id.qq_enter_tv);
        imageView = (ImageView) findViewById(R.id.eye_code);
        imageViewClose = (ImageView) findViewById(R.id.eye_code_close);
        textView_phone_login = (TextView) findViewById(R.id.phone_login);
        imageView.setVisibility(View.VISIBLE);
        imageViewClose.setVisibility(View.INVISIBLE);
        imageView.setOnClickListener(this);
        imageViewClose.setOnClickListener(this);
        textViewF.setOnClickListener(this);
        textViewR.setOnClickListener(this);
        textViewQ.setOnClickListener(this);
        btn.setClickable(false);
        btn.setTextColor(Color.GRAY);
        log = new LogBase(this);

        // 如果用户名改变，清空密码
        editPerson.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                editCode.setText(null);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        editCode.addTextChangedListener(new EditChangedListener());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.enter_btn:
                login(v);
                break;
            case R.id.eye_code:
                num = String.valueOf(editCode.getText());
                imageView.setVisibility(View.INVISIBLE);
                imageViewClose.setVisibility(View.VISIBLE);
                editCode.setInputType(131073);
                break;
            case R.id.eye_code_close:
                imageView.setVisibility(View.VISIBLE);
                imageViewClose.setVisibility(View.INVISIBLE);
                editCode.setInputType(129);
                break;
            case R.id.forget_code:

                break;

            case R.id.register_tv:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
//                startActivityForResult(new Intent(this, RegisterActivity.class), 0);
                break;

            case R.id.qq_enter_tv:

                break;
            case R.id.phone_login:

                break;
        }
    }

    class EditChangedListener implements TextWatcher {

        private CharSequence temp; // 监听前的文本


        // 输入文本之前的状态
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            temp = s;
        }

        // 输入文字中的状态，count是一次性输入字符数
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String name = editCode.getText().toString().trim();
            if (6 - name.length() <= 0) {
                btn.setClickable(true);
                btn.setTextColor(Color.WHITE);
            } else {
                btn.setClickable(false);
                btn.setTextColor(Color.GRAY);
            }
        }

        // 输入文字后的状态
        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin) {
            return;
        }
    }

    /**
     * 登录
     *
     * @param view
     */
    public void login(View view) {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, "网络链接错误", Toast.LENGTH_SHORT).show();
            return;
        }
        currentUsername = editPerson.getText().toString().trim();
        currentPassword = editCode.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        progressShow = true;
        final ProgressDialog pd = new ProgressDialog(EnterActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                progressShow = false;
            }
        });
        pd.setMessage("正在登录....");
        pd.show();

        final long start = System.currentTimeMillis();
        // 调用sdk登陆方法登陆聊天服务器
        EMChatManager.getInstance().login(currentUsername, currentPassword, new EMCallBack() {

            @Override
            public void onSuccess() {
                if (!progressShow) {
                    return;
                }
//                 登陆成功，保存用户名 和密码
//                user = new User(AllSingleTon.getOurInstance().getDaoSession().getAllDaos().size().count(),editPerson.getText().toString(),editCode.getText().toString());
//                AllSingleTon.getOurInstance().getDaoSession().getUserDao().insert(user);
                //注册群组和联系人监听
//               JianTingEnter jianTingEnter = new JianTingEnter();
//                jianTingEnter.registerGroupAndContactListener();

//
                // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                // ** manually load all local groups and
                EMGroupManager.getInstance().loadAllGroups();
                EMChatManager.getInstance().loadAllConversations();

                if (!EnterActivity.this.isFinishing() && pd.isShowing()) {
                    pd.dismiss();
                }
                // 进入主页面
                Intent intent = new Intent(EnterActivity.this,
                        MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                if (!progressShow) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(), "登陆失败：" + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


}
